package com.yimi.yinhepda.views.setting_module;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.pda.ym.base.BaseTitleActivity;
import com.pda.ym.utils.SysInfo;
import com.pda.ym.base.BaseActivity;
import com.yimi.yinhepda.R;
import com.pda.ym.callbacks.UICallBack;
import com.yimi.yinhepda.entity.response.QueryLoginInfoResponse;
import com.pda.ym.net.NetRequest;
import com.yimi.yinhepda.utils.Common;
import com.pda.ym.utils.Constants;
import com.yimi.yinhepda.utils.GpsUtil;
import com.pda.uce.commom.util.MyDialog;
import com.pda.ym.utils.NetworkUtil;

import org.jetbrains.annotations.NotNull;

import java.util.HashMap;
import java.util.Map;

/**
 * PDA本机信息界面
 *
 * @author 000432
 */
public class PdaInfoActivity extends BaseTitleActivity {
    private TextView loginEmp;
    private TextView logingStatin;
    private TextView currentVersion;
    private TextView deviceId;
    private TextView et_worknum;
    /**
     * 设备型号
     */
    private TextView mDeviceModle;
    private EditText etAPMAC;
    private EditText etDeptName;
    private EditText etPhone;
    private static final int REQUEST_CODE_LOCATION_SETTINGS = 100;
    private static final int REQUEST_CODE_LOCATION_PER = 102;
    /**
     * 硬件标识请求权限标志
     */
    private static final int RQUEST_HARDWARE_PERMISSION = 101;
    /**
     * 硬件标识权限请求次数
     */
    private int hardwarePerCount;

    @Override
    public String getPageName() {
        return "本机信息";
    }

    @Override
    public int setContentViewId() {
        return R.layout.activity_pda_info;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        etAPMAC = findViewById(R.id.et_ap_mac);
        EditText etLocalMac = findViewById(R.id.et_local_mac);
        etAPMAC.setText(SysInfo.getInstance().getNetMac());
        etLocalMac.setText(NetworkUtil.getMacAddr());

        loginEmp = findViewById(R.id.login_emp);
        logingStatin = findViewById(R.id.login_station);
        etDeptName = findViewById(R.id.et_deptName);
        currentVersion = findViewById(R.id.current_version);
        deviceId = findViewById(R.id.device_id);
        et_worknum = findViewById(R.id.et_worknum);
        mDeviceModle = findViewById(R.id.device_modle);
        etPhone = findViewById(R.id.et_phone);

        loginEmp.setText(sharedPreferUtil.getEmpName());
        logingStatin.setText(sharedPreferUtil.getDeptCode());
        etDeptName.setText(sharedPreferUtil.getValue(Common.DEPT_NAME));
        currentVersion.setText(SysInfo.getInstance().getVersionName());
        deviceId.setText(SysInfo.getInstance().getImei());
        et_worknum.setText(sharedPreferUtil.getWorkNum());
        mDeviceModle.setText(SysInfo.getInstance().getPhoneModel());

        findViewById(R.id.btn_ok).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        requestHardwareFlagPermission();

        //查询登录用户信息
        queryLoginInfo();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case RQUEST_HARDWARE_PERMISSION:
                //硬件标识符请求权限
                if ((grantResults.length > 0) && (grantResults[0] != PackageManager.PERMISSION_GRANTED)) {
                    if (hardwarePerCount < 5) {
                        hardwarePerCount++;
                        ActivityCompat.requestPermissions(this,
                                new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, RQUEST_HARDWARE_PERMISSION);
                    } else {
                        //提示打开位置权限
                        openGpsPermissionDialog();
                    }
                }
                break;
            default:
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_LOCATION_SETTINGS) {
            checkGpsIsOpen();
        } else if (requestCode == REQUEST_CODE_LOCATION_PER) {
            requestHardwareFlagPermission();
        }
    }

    private void requestHardwareFlagPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED ||
                    ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION,
                        Manifest.permission.ACCESS_COARSE_LOCATION}, RQUEST_HARDWARE_PERMISSION);
            } else {
                checkGpsIsOpen();
            }
        }
    }

    /**
     * 查询用户登录信息
     */
    private void queryLoginInfo() {
        showPgDlg("查询中...");
        Map<String, String> params = new HashMap<>();
        new NetRequest().setMethod(NetRequest.Method.GET)
                .setResponsClazz(QueryLoginInfoResponse.class)
                .setUrl(Constants.URL_LOGIN_INFO)
                .setParams(params)
                .execute(new UICallBack() {
                    @Override
                    public void onError(String msg) {
                        dismissPgDlg();
                        showToast(msg);
                    }

                    @Override
                    public void onSuccess(Object obj) {
                        dismissPgDlg();
                        QueryLoginInfoResponse response = (QueryLoginInfoResponse) obj;
                        if (response.getData() != null) {
                            if (response.getData().getSessionAttrs() != null) {
                                if (response.getData().getSessionAttrs().getLoginUser() != null) {
                                    QueryLoginInfoResponse.DataBean.SessionAttrsBean.LoginUserBean userBean = response.getData().getSessionAttrs().getLoginUser();
                                    etPhone.setText(userBean.getPhoneNum());
                                }
                            }
                        }
                    }
                });
    }

    /**
     * 手动打开位置权限提示
     */
    private void openGpsPermissionDialog() {
        MyDialog dialog = new MyDialog(this);
        dialog.setIcon(R.drawable.alert);
        dialog.setDialogType(MyDialog.DialogType.ALERT_DIALOG);
        dialog.setTitle("提示");
        dialog.setMessage("需要授权位置权限才可以获取APMAC地址！");
        dialog.setPositiveClickListener("去打开", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                Uri packageURI = Uri.parse("package:" + getPackageName());
                Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, packageURI);
                startActivityForResult(intent, REQUEST_CODE_LOCATION_PER);
            }
        });
        dialog.setNegativeClickListener(R.drawable.btn_login_selector, "取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                openGpsPermissionDialog();
            }
        });
        dialog.setCanceledOnTouchOutside(false);
        dialog.setCancelable(false);
        dialog.show();
    }

    /**
     * 打开GPS
     */
    private boolean checkGpsIsOpen() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            //android6.0以上需要位置权限获取APMAC进行打卡
            if (!GpsUtil.isOPen(this)) {
                MyDialog dialog = new MyDialog(this);
                dialog.setIcon(R.drawable.alert);
                dialog.setDialogType(MyDialog.DialogType.ALERT_DIALOG);
                dialog.setTitle("提示");
                dialog.setMessage("需要打开GPS位置功能才可以获取APMAC地址！");
                dialog.setPositiveClickListener("去打开", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        Intent locationIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                        startActivityForResult(locationIntent, REQUEST_CODE_LOCATION_SETTINGS);
                    }
                });
                dialog.setNegativeClickListener(R.drawable.btn_login_selector, "取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        checkGpsIsOpen();
                    }
                });
                dialog.setCanceledOnTouchOutside(false);
                dialog.setCancelable(false);
                dialog.show();
                return false;
            } else {
                SysInfo.getInstance().init(this);
                etAPMAC.setText(SysInfo.getInstance().getNetMac());
            }
        }
        return true;
    }

    @Override
    public boolean showBack() {
        return false;
    }

    @Override
    public void setBack() {

    }

    @NotNull
    @Override
    public String setTitle() {
        return getPageName();
    }

}
